<?php
namespace common\models;


use common\bonus\BaseBonus;
use common\utils\CommonFun;
use console\controllers\ReleaseController;

class GroupDetail extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'group_detail';
    }


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [[ 'commodity_id','group_money','member_id'], 'required'],
            [['commodity_id', 'create_time', 'update_time'], 'integer'],
            [['group_time'],'string'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'group_detail_id' => '拼团订单详情表id',
            'commodity_id' => '合约配置表id',
            'finalist_id' => '入围人员id',
            'member_id'   =>'参与人员id',
            'winning_id'  => '中奖人员id',
            'group_money' =>'拼团金额',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'group_time'  => '活动时间',
        ];
    }    

	/*
		* 数据列表
		* whereArr 条件
		* params 基本参数 包含 field order page limit
		* extends  扩展信息 一些相关的信息
		* 
	*/	
	public static function dataList($whereArr, $params, $extends = array())
	{
		$model  = self::find();
		$where  = isset($whereArr['where']) ? $whereArr['where'] : [];
		$whereAnd = isset($whereArr['and'])?$whereArr['and']:[];


		if (isset($where['list_status'])){
            $list_status = $where['list_status'];

            $time = time();

		    //我参加的
		    if ($where['list_status']==1){
                $where=(['or' , 'member_id = "'.$params['member_id'].'"' , 'member_id like "%'.$params['member_id'].'%"']);
		     //我中奖
            }elseif ($where['list_status']==2){
                $where=(['or' , 'winning_id = "'.$params['member_id'].'"' , 'winning_id like "%'.$params['member_id'].'%"']);

		     //我入围
            }elseif($where['list_status']==3){
                $where=(['or' , 'finalist_id = "'.$params['member_id'].'"' , 'finalist_id like "%'.$params['member_id'].'%"']);

            }

        }

		$models = self::queryFormart($model,$where,$params,$whereAnd);
		$model  = $models['model'];

		$data  = $model->asarray()->all();

		if(!$data) return array();

		//扩展信息
		if(!$extends) return $data;

        foreach ($data as $k=>$v){

		foreach($extends as $extend) {
		    if ($extend=='winning') {
                $winningWhere = 'group_detail_id=' . $v['group_detail_id'] . '
		     and member_id=' . $params['member_id'] . " 
		     and winning_time>='" . $v['group_time'] . " 00:00:00'" . " and winning_time<'" . date('Y-m-d H:i:s', time()) . "'";

                $winningInfo = GroupWinning::getOne($winningWhere);

                $finalistArr=[];
                if ($v['finalist_id'])
                    $finalistArr = explode(',',$v['finalist_id']);
                if ($list_status == 1) {
                    if ($winningInfo) {
                        unset($data[$k]);
                        continue;
                    }


                    if(in_array($params['member_id'],$finalistArr)) {
                        unset($data[$k]);
                        continue;
                    }
                    $data[$k]['status_text'] = '未中奖';
                }

                if ($list_status == 2) {
                    if ($winningInfo) {
                        $data[$k]['winning_id'] = $winningInfo['id'] ?? 0;
                        $data[$k]['winning_time'] = $winningInfo['winning_time'] ?? '';
                        $data[$k]['status_text'] = '已中奖';
                        $data[$k]['is_winning'] =1;
                        $data[$k]['is_order'] =  $winningInfo['is_order']==2?'1':'0';
                    } else {
                        unset($data[$k]);
                        continue;
                    }
                }
                if ($list_status == 3) {
                    if(in_array($params['member_id'],$finalistArr)) {
                        $data[$k]['status_text'] = '已入围';
                    } else {
                        unset($data[$k]);
                        continue;
                    }
                }
            }
             if ($extend=='home_list'){
                 $field =  'sell_start_time,sell_end_time,finalist_income,day_income';
                 $commodityArr = TradeCommodity::getOne(['commodity_id'=>$v['commodity_id']],$field);
                 $data[$k]['sell_start_time'] = $commodityArr['sell_start_time'];
                 $data[$k]['sell_end_time']   = $commodityArr['sell_end_time'];
                 $data[$k]['finalist_income'] = $commodityArr['finalist_income'];
                 $data[$k]['day_income']      = $commodityArr['day_income'];
                 $data[$k]['winning_count']   = 0;
                 $data[$k]['finalist_count']  = 0;
                 if ($v['winning_id']) {
                     $data[$k]['winning_count'] = count(explode(',', $v['winning_id']));
                 }
                 if ($v['finalist_id']) {
                     $data[$k]['ruwei_count']    = GroupFinalist::find()->where(['group_detail_id'=>$v['group_detail_id']])->count();
                     $data[$k]['finalist_count'] = count(array_unique(explode(',', $v['finalist_id'])));
                 }
             }
		}
        }
   sort($data);
		return $data;	
	}


    public static function getOne($where, $field = ['*'])
	{
		return self::find()->select($field)->where($where)->asarray()->one();
	}


	public static function getAll($where = [], $field = ['*'])
	{
		return self::find()->select($field)->where($where)->asarray()->all();
	}

    /**
     * 参加拼团
     * @param $data  拼团数据
     * @param $member 用户信息
     * @return bool|mixed  是否拼团成功
     */
	public function userSetGroup($data,$member){

	    if (!$member) return false;
	    /*判断当天该活动有没有数据*/
        $where  = "commodity_id=".$data['commodity_id'].' and group_time="'.date('Y-m-d',time()).'"';
        $info   =  self::find()->select('*')->where($where)->one();

        if ($info){
            $insertArr = [
                'group_detail_id'=> $info['group_detail_id'],
                'member_id'     => $info['member_id'].','.$member['member_id'],
                'update_time'    => time()
            ];

          $re =$info->load($insertArr,'') && $info->save();

          if($re) return $info['group_detail_id'];

        }else
        {
            $insertArr=[
                'commodity_id'  => $data['commodity_id'],
                'member_id'     => $member['member_id'],
                'group_time'    => date('Y-m-d',time()),
                'group_money'   =>$data['money_up'],
                'create_time'   => time(),
                ];
           $this->load($insertArr,'')&&$this->save();
           return $this->attributes['group_detail_id'];
        }

    }

    public function userCancelGroup($data,$member){
	    $memberList = explode(',',$data['member_id']);

	    if (count($memberList)==1){
           return $this->deleteAll(['group_detail_id'=>$data['group_detail_id']]);
        }else{

            $update = implode(',',array_diff($memberList,[$member]));
	      return  $this->updateAll(['member_id'=>$update],['group_detail_id'=>$data['group_detail_id']]);
        }
    }

    /**
     * 未中奖人员数据处理
     *
     * @param $data 需要做处理当天所有的数据
     */
    public function finalist($data){

        //获取所有的活动ID
        $commodityArr  = array_column($data,'commodity_id');
        $CommodityInfo = TradeCommodity::getAll(['commodity_id'=>$commodityArr],'finalist_income,commodity_id');
        $conf          = TradeModel::getStaticReleaseConf('StaticRelease');
        $assignType    = json_decode($conf['assign_type'],1);

        if (count($assignType)<1) false;

        /*每个活动的未中收益比*/
        $group         = [];
        foreach ($CommodityInfo as $gk=>$gv) {
            $group[$gv['commodity_id']]=$gv['finalist_income'];
        }


        /*循环拼团数据*/
        foreach ($data as $k => $v) {
            $memberArr=[];
            $winningArr =[];

            if ($v['winning_id']) $winningArr   = explode(',',$v['winning_id']);

            $memberArr = explode(',',$v['member_id']);
            $userArr   = array_diff($memberArr,$winningArr);

            /*未中奖人员返回本金*/
            if ($userArr){
                foreach ($userArr as $uk=>$uv){
                    $balanceLog  =BalanceLog::updateAll(['is_lock'=>0],"source_id=".$v['group_detail_id']." and member_id=".$uv." and source_type=6 and is_lock=1");
                    /*用户返回余额*/
                    $res =Balance::addBalance($uv,1,$v['group_money'],7,$v['group_detail_id'],$from='',true);

                    if(!$res['state']) {
                        CommonFun::writeLog($uv . '该用户增加余额失败');
                        continue;
                    };
                }
            }

            $end_time       = date('Y-m-d 23:59:59',time());
           $where          ='group_detail_id='.$v['group_detail_id']." and finalist_time>='".$v['group_time'].' 00:00:00'."' and finalist_time<='$end_time'";
            $finalistArr    = GroupFinalist::getAll($where,'member_id');
            if (empty($finalistArr))  continue;
            $finalistUser       = array_column($finalistArr,'member_id');
            $finalistCommodity  =array_unique($finalistUser);

           /*收益循环*/
            foreach ($finalistUser as $fk=>$fv) {
                $bonus = bcdiv(bcmul($v['group_money'],$group[$v['commodity_id']],2),100,4);

                if($bonus<=0) continue;
                /*未中收益加速*/
                $this->release($bonus,$fv,$v['commodity_id'],$conf,$assignType,5);
            }


            foreach ($finalistCommodity as $cok=>$cov){
                $whereArr['where']='member_id='.$cov.' and order_type<>1 and status=1';
                $contract = StaticInstance::dataList($whereArr,[],['find']);

                if ($contract){
                    $commodityId = 0;
                    $ids         = 0;
                    $bonus_days  = 0;
                    foreach ($contract as $cck=>&$ccv){
                        /*算出最近过期的合同*/
                        $time = strtotime($ccv['create_time']);
                        $period_day =$ccv['period_day']??0;
                        $ccv['day'] =date('Y-m-d H:i:s',strtotime('+ '.$period_day.'day',$time));
                    }
                    $times =array_column($contract,'day');

                    /*对数组进行排序*/
                   array_multisort($times,SORT_ASC,$contract);

                    foreach ($contract as $ck=>$cv) {
                        if ($v['group_money']<$cv['in_num']) continue;
                        $commodityId = $cv['commodity_id'];
                        $ids         = $cv['id'];
                        $bonus_days  = $cv['bonus_day'];
                        $group_money = $cv['in_num'];
                        $was_num     = $cv['was_num'];
                        break;
                    }

                    if (!$commodityId) continue;
                    if (!$ids) continue;

                    /*释放加速合约的静态收益*/
                    $commodityInfo = TradeCommodity::getOne(['commodity_id'=>$commodityId],'day_income,commodity_id');

                    $commodity[$commodityInfo['commodity_id']] = $commodityInfo['day_income'];
                    $money = bcmul($group_money,$commodity[$commodityId],4)/100;

                    $bonus_days+=1;
                    $was_num+=$money;
                    StaticInstance::updateAll(['bonus_day'=>$bonus_days,'was_num'=>$was_num],'id='.$ids);

                    if($money<=0) continue;
                    $this->release($money,$cov,$commodityId,$conf,$assignType,8,1);
                }
            }

            $update = ['status'=>2,'update_time'=>time()];
            $this->updateAll($update,['group_detail_id'=>$v['group_detail_id']]);

        }
        return true;
    }


    /**
     * 收益
     *
     */
    public function release($bonus,$memer_id,$commodity_id,$conf,$assignType,$model_id,$category=0){

        $member = Member::getMemberById($memer_id,['member_name','member_id','member_email']);
        $params                 = array();
        $params['money']        = $bonus;
        $params['member_id']    = $memer_id;
        $params['source_id']    = $commodity_id;
        $params['mch_id']       = 0;
        $params['trigger_type'] = $conf['next_action'];
        $params['desc']         = 'from 【'.$member['member_name'].'】';
        $params['model_id']     = $model_id;
        $params['category']     = $category;
        /*用户返 未中收益*/
        foreach($assignType as $btype=>$rate)
        {
            $balance = round($bonus * $rate / 100 , 2);
            if ($model_id==5) {
                $res = Balance::addBalance($memer_id, $btype, $balance, 22, $commodity_id);
            }else
            {
                $res = Balance::addBalance($memer_id, $btype, $balance, 8, $commodity_id);
            }
            if(!$res['state']){
                $str = '静态释放 instance_id:'.$commodity_id."\r\n conf:".json_encode($conf).'msg:'.$res['msg'];
                CommonFun::writeLog($str,'bonus');
            }
        }

        //用户返 未中收益触发后续加速
        if($conf['next_action']>0){
            BaseBonus::bonusRun($params);
        }
    }

}